// Copyright  Author(https://github.com/LiuShuKu). All Rights Reserved.

// Copyright (c)  2024 LiuShuKu
// Project Name :   balance
// Author       :   liushuku@yeah.net

// Package core .
package core

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcache"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtimer"
	"os"
	"time"
	"tronServer/internal/consts"
	_ "tronServer/internal/logic"
	"tronServer/internal/service"
)

type tronMonitor struct {
}

var TronMonitor = &tronMonitor{}

var (

	// MonitorWalletsAddress 监控地址
	MonitorWalletsAddress = []string{
		"TLdDDCtxZeNzEh3vjpAEYxavRTvK2iQoqj",
		"TMwsC5hpQ3shbUQJ34FcZWDiJWPvAgV587",
	}

	// NotificationAddress  通知地址
	NotificationAddress = []string{
		"http://127.0.0.1:8000/callback/tronTrc20Callback",
	}
)

func (t *tronMonitor) Run(ctx context.Context) {
	initMonitorWalletsAddress(ctx)
	initNotificationAddress(ctx)
	gtimer.AddSingleton(ctx, time.Second, func(ctx context.Context) {
		initUsdtTransactionMonitoring(ctx)
		time.Sleep(5 * time.Second)
	})
	select {}
}

// initMonitorWalletsAddress 初始化监控钱包地址
func initMonitorWalletsAddress(ctx context.Context) {
	err := gcache.Set(ctx, consts.MonitorWalletsAddressKey, MonitorWalletsAddress, 0)
	if err != nil {
		glog.Errorf(ctx, " 初始化监控钱包地址失败 %s", err.Error())
		os.Exit(0)
	}
	glog.Infof(ctx, " 初始化监控钱包地址成功 %s", gcache.MustGet(ctx, consts.MonitorWalletsAddressKey).Strings())
}

// initNotificationAddress 初始化通知地址
func initNotificationAddress(ctx context.Context) {
	err := gcache.Set(ctx, consts.NotificationAddressKey, NotificationAddress, 0)
	if err != nil {
		glog.Errorf(ctx, "初始话通知地址失败 %s", err.Error())
		os.Exit(0)
	}
	glog.Infof(ctx, "初始话通知地址成功 %s", gcache.MustGet(ctx, consts.NotificationAddressKey).Strings())
}

// UsdtTransactionMonitoring 初始化USDT交易监控
func initUsdtTransactionMonitoring(ctx context.Context) {
	var (
		monitorWallets            *g.Var
		monitorWalletsAddressList []string
	)
	g.Log().Info(ctx, "<--USDT交易监控-开始-->")
	monitorWallets, err := gcache.Get(ctx, consts.MonitorWalletsAddressKey)
	{
		if err != nil {
			g.Log().Errorf(ctx, "获取监控钱包地址失败 %s", err.Error())
			os.Exit(0)
		}
	}
	{
		monitorWalletsAddressList = monitorWallets.Strings()
	}
	for _, address := range monitorWalletsAddressList {
		addressNew := address
		go func() {
			err = service.Tron().DisposeUsdtTransactionRecords(ctx, addressNew)
			if err != nil {
				g.Log().Errorf(ctx, "监控钱包地址 %s 失败 %s", addressNew, err.Error())
				return
			}
		}()
	}
}
